using System;
using System.Collections;
using System.Collections.Generic;

namespace Rhizome.Model
{
	public abstract class CounterBase<TValue, TStep> : PropertyActiveItemBase
	{
		private TValue _memory;
		private bool _memoryHasValue;
		public TStep Step { get; set; }
		public TimeSpan Interval { get; set; }
		public bool UseMemory { get; set; }

		protected override sealed IEnumerator Steps()
		{
			var ms = (int) Interval.TotalMilliseconds;
			var plant = Plant;
			_memoryHasValue = false;

			while (true)
			{
				Increment(plant);
				Sleep(ms);
				yield return null;
			}
		}

		protected virtual void Increment(object plant)
		{
			if (UseMemory == false || _memoryHasValue == false)
			{
				_memory = (TValue) (PropertyInfo.GetValue(plant, null));
				_memoryHasValue = true;
			}
			_memory = CountValue(_memory);
			PropertyInfo.SetValue(plant, _memory, null);
		}

		protected abstract TValue CountValue(TValue old);

	}
}